﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.AccessControl;
using Google.Documents;
using Google.Contacts;
using DataType;
using System.IO;
using System.Web.Mail;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Soap;
using LicenseManager;
using System.Xml.Linq;
using System.Globalization;

using VSTO = Microsoft.Office.Tools.Word;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Word.Extensions; 

namespace OfficeInCloudWord2007
{
    public partial class MyGDocsForm : UserControl
    {
      
            // this code assumes the following using statements
            //      using System.Collections;
            //      using System.Windows.Forms;

            // return all the controls in a control container
            // (including controls inside other controls)
        public static ArrayList GetChildControls(Control ctrl, Type ctrlType)
            {
               ArrayList controls = new ArrayList();
               foreach (Control c in ctrl.Controls)
               {
                  if ( ctrlType == null || ctrlType.IsAssignableFrom(c.GetType()))
                  {
                     // add this control and all its nested controls
                     controls.Add(c);
                     controls.AddRange(GetChildControls(c, null));
                  }
               }
               // return the result as a Control array
               //return (Control[]) controls.ToArray(typeof(Control));
               return controls;
            }
        
        class UIState
        {
            private Control[] m_ctrlsDefault;
            private Dictionary<string, Control[]> m_StateMap;

            public UIState(Control[] ctrls)
            {
                m_StateMap = new Dictionary<string, Control[]>();
                m_ctrlsDefault = new System.Windows.Forms.Control[ctrls.Length];
                for (int i = 0; i < ctrls.Length; ++i)
                {
                    m_ctrlsDefault[i] = new System.Windows.Forms.Control();
                    m_ctrlsDefault[i] = ctrls[i];
                }
            }

            public void SetState(string pathName, ControlCollection ctrlsOrig)
            {
                if (pathName.Length > 0)
                {
                    Control[] ctrls = new Control[ctrlsOrig.Count];
                    for (int i = 0; i < ctrlsOrig.Count; ++i)
                    {
                        ctrls[i] = new Control();
                        ctrls[i] = ctrlsOrig[i];
                    }

                    m_StateMap[pathName] = ctrls;
                }
            }

            public Control[] GetState(string pathName)
            {
                if (pathName.Length == 0)
                    return m_ctrlsDefault;

                Control[] ctrls = new Control[m_ctrlsDefault.Count()];
                // if new workbook is opened the load the default UI scheme
                if (!m_StateMap.TryGetValue(pathName, out ctrls))
                {
                    m_StateMap.Add(pathName, m_ctrlsDefault);
                    ctrls = m_ctrlsDefault;
                }

                return ctrls;
            }
        }

        public WordLocalView m_LocalView;
        public ThreadSafeUIOperations m_TS_UI;
        public TreeViewDocuments m_Tree;
        private Credentials m_Cred;
        private UIState m_currentState;
        System.Windows.Forms.Button m_copyBtn;

        public MyGDocsForm(WordLocalView LocalView, bool disabled)
        {
            InitializeComponent();

            m_LocalView = LocalView;
            m_LocalView.m_LoadState += new WordLocalView.StateNotify(SetUIState);
            m_LocalView.m_StoreState += new WordLocalView.StateNotify(GetUIState);
            
            m_Tree = new TreeViewDocuments(this.documentsView);
            m_TS_UI = new ThreadSafeUIOperations();
            readerRadioButton.Checked = true;
            //LoginProgress.Visible = true;
            UpdateBtn.Enabled = false;
            RefreshButton.Enabled = false;
            RegistrationLink.Visible = false;
            ShareButton.Enabled = false; 

            Credentials cred = new Credentials(null, null);
            m_LocalView.DoLoadCredentials(cred);

            if (cred.m_remember == true) {
                UserName.Text = cred.m_Cred.Username;
                Password.Text = cred.m_password;
                checkRemember.Checked = cred.m_remember; 
            }

            if (disabled)
            {
                UserName.Enabled = false;
                Password.Enabled = false;
                checkRemember.Enabled = false;
                LoginButton.Enabled = false;
                RegistrationLink.Visible = true;
            }

            //create default UI state after login completed
            MyGDocsForm copyForm = (MyGDocsForm)this.MemberwiseClone();
            ArrayList sharedArr = GetChildControls(copyForm.ShareTab, null);
            ArrayList updateArr = GetChildControls(copyForm.UpdateTab, null);
            
            ArrayList resultArr = new ArrayList();
            resultArr.AddRange(sharedArr);
            resultArr.AddRange(updateArr);
            
            //Stream stream = File.Open("ApplicationName.xml", FileMode.Create);
            //SoapFormatter formatter = new SoapFormatter();

            //formatter.Serialize(stream, resultArr);
            //stream.Close();

            //formatter = new SoapFormatter();
            //ArrayList resultArr1 = new ArrayList();
            //stream = File.Open("ApplicationName.xml", FileMode.Open);
            //resultArr1 = (ArrayList)formatter.Deserialize(stream);

            //stream.Close();

            Control[] origCtrl = (Control[])resultArr.ToArray(typeof(Control));
            Control[] resultCtrl = new Control[origCtrl.Length];
            for (int i = 0; i < origCtrl.Length; ++i)
            {
                resultCtrl[i] = new Control();
                resultCtrl[i] = origCtrl[i];
            }

            m_currentState = new UIState(resultCtrl);
        }

        public void GetUIState(string pathName)
        {
                m_currentState.SetState(pathName, this.Controls);
        }

        public void SetUIState(string pathName)
        {
            Control[] stateCtrl = m_currentState.GetState(pathName);

            //it's expected that every control has unique name, so every time only one element in array
            foreach (Control current in stateCtrl)
            {
                long count = 0;
                if (current.Name == "ContactListBox")
                    count = ((CheckedListBox)current).CheckedItems.Count;
                Control[] ctr = this.Controls.Find(current.Name, true);
                this.Controls.Remove(ctr[0]);
                ctr[0] = current;
            }
        }

        private void MyGDocsForm_Resize(object sender, EventArgs e)
        {
            this.MyGDocsTabControl.Size = this.Size;
        }

        private void AddListBoxItem(string Msg, bool CheckState)
        {
            this.ContactListBox.Items.Add(Msg, false);
        }

        //private void SwitchOnProgress(PictureBox pb) {
        //    pb.Visible = true; 
        //} 

        private void AddContact2UI(Contact contact)
        {
            if (contact.ContactEntry.Emails[0].Address.Length == 0)
                return;
            else
                m_TS_UI.AddListBoxItem(this.ContactListBox, contact.ContactEntry.Emails[0].Address, false);
        }

        private void BuildContacts()
        {
            FeedWrapper<Contact> feed = new FeedWrapper<Contact>();
            m_LocalView.DoGetContacts(feed);
            foreach (Contact cnt in feed.m_Feed.Entries)
                AddContact2UI(cnt);
            //m_LocalView.DoGetContactsAsync(this.AddContact2UI);
        }

        private void BuildDocuments()
        {
            
            m_Tree.InitTree();
            FeedWrapper<Document> feed = new FeedWrapper<Document>();
            m_LocalView.DoGetDocuments(feed);

            foreach (Google.Documents.Document entry in feed.m_Feed.Entries) m_Tree.AddDocumentToCollection(entry);

            m_Tree.ShowTree();
        }

        private void BuildDataStructure()
        {
            BuildContacts();
            BuildDocuments();
        }

        public void button1_Click(object sender, EventArgs e)
        {
            m_TS_UI.SetVisible(StatusMessage, false);
            m_TS_UI.SetEnabled(LoginButton, false);
            //LoginProgress.Visible = true;
            m_TS_UI.SetEnabled(UserName, false);
            m_TS_UI.SetEnabled(Password, false);
            m_TS_UI.SetEnabled(checkRemember, false);
            m_TS_UI.SetEnabled(RefreshButton, false); 

            try
            {
                LicenseManager.ZohoLicenseManager lm = new ZohoLicenseManager("info@upriseapps.com", "mamamilaramu");
                lm.Login();
                if (lm.RegisteredContactBlocked(this.m_LocalView.m_db))
                    throw new ZohoLicenseBlocked();

                m_Cred = new Credentials(UserName.Text, Password.Text);
                
                if (checkRemember.Checked) m_Cred.m_remember = true;
                else m_Cred.m_remember = false;

                ContactListBox.Items.Clear();
                m_Tree.CleanUp();

                m_TS_UI.SetEnabled(ShareButton, false);

                m_LocalView.DoLogin(m_Cred);

                // save credentials for future purposes.
                if (m_Cred.m_remember)
                    m_LocalView.DoSaveCredentials(m_Cred);

                m_TS_UI.SetEnabled(ShareButton, true);
                m_TS_UI.SetForeColor(StatusMessage, Color.Black);
                m_TS_UI.SetText(StatusMessage, Properties.Resources.LoginSucceeded);

                m_TS_UI.SetEnabled(RefreshButton, true); 

                BuildDataStructure();

                MyGDocsTabControl.SelectTab("Explorer"); 
            }
            catch (AuthenticationException ex)
            {
                m_TS_UI.SetEnabled(ShareButton, false);
                m_TS_UI.SetForeColor(StatusMessage, Color.Red);
                m_TS_UI.SetText(StatusMessage, Properties.Resources.ErrorPrefix + ex.Message);
                m_TS_UI.SetEnabled(RefreshButton, false);
            }
            catch (ZohoLicenseBlocked ex)
            {
                MessageBox.Show("We are sorry but your Office In Cloud license is blocked. \n" +
                                 "Please contact Uprise Apps support: info@upriseapps.com for details."); 
            }
            catch (Exception ex)
            {
                m_TS_UI.SetEnabled(ShareButton, false);
                m_TS_UI.SetForeColor(StatusMessage, Color.Red);
                m_TS_UI.SetText(StatusMessage, Properties.Resources.ErrorPrefix + ex.Message);
                m_TS_UI.SetEnabled(RefreshButton, false);
            }
            finally
            {
                m_TS_UI.SetVisible(StatusMessage, true);
                m_TS_UI.SetEnabled(LoginButton, true);
                m_TS_UI.SetEnabled(UserName, true);
                m_TS_UI.SetEnabled(Password, true);
                m_TS_UI.SetEnabled(checkRemember, true);
                m_TS_UI.SetEnabled(UpdateBtn, true); 
            }
        }

        private void ShareDocument()
        {
            WordLocalView.Permission perm = WordLocalView.Permission.writer;
            if (readerRadioButton.Checked)
                perm = WordLocalView.Permission.reader;

            string[] users = new string[ContactListBox.CheckedItems.Count];
            for (int i = 0; i < ContactListBox.CheckedItems.Count; ++i)
            {
                users[i] = ContactListBox.CheckedItems[i].ToString();
            }

            m_LocalView.DoShareDocumentsAsync(ContactListBox.CheckedItems, perm);
        }

        private enum MailNotificationTypes { Share, Update }

        private void SendNotification(AclFeed feed, 
                                      string CustomSubject, 
                                      string CustomBody, 
                                      string docURL, 
                                      string docName, 
                                      MailNotificationTypes mailType)
        {
            System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();

            foreach(AclEntry entry in feed.Entries)
                mail.To += (entry.Scope.Value + ";");

            if (!this.m_Cred.m_Cred.Username.Contains("@"))
                mail.From = this.m_Cred.m_Cred.Username + "@gmail.com";
            else
                mail.From = this.m_Cred.m_Cred.Username;
            //System.Windows.Forms.MessageBox.Show("From = " + mail.From);
            
            
            if (CustomSubject.Trim().Length == 0)
                mail.Subject = docName;
            else
	            mail.Subject = CustomSubject;

            switch (mailType)
            {
                case MailNotificationTypes.Share:
                    mail.Body = Properties.Resources.MsgSharePrefix; 
                    break;
                case MailNotificationTypes.Update:
                    mail.Body = Properties.Resources.MsgUpdatePrefix;
                    break; 
            }

            if (CustomBody.Trim().Length != 0)
            {
                mail.Body += "\n";
                mail.Body += CustomBody;
            }

            mail.Body += "\n";
            mail.Body += "\n"; 
            mail.Body += docName;
            mail.Body += "\n";
            mail.Body += docURL;
            mail.Body += "\n";
            mail.Body += "\n";
            mail.Body += "From Uprise Apps Office In Cloud";

            //Ensure priority is set to "NORMAL
            mail.Priority = MailPriority.Normal;
            //  Use Authentication
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use this Username to Authenticate
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", this.m_Cred.m_Cred.Username);
            //Use this Password to Authenticate
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", this.m_Cred.m_password);
            //Use STARTTLS (some clients call this SSL) - Gmail help page indicated it used this
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
            // assign outgoing gmail server
            SmtpMail.SmtpServer = "smtp.gmail.com";
            SmtpMail.Send(mail);  
        }

        public void ShareButton_Click(object sender, EventArgs e)
        {
            m_TS_UI.SetEnabled(ShareButton, false);
            m_TS_UI.SetVisible(StatusMsgShare, false);

            bool newFile = false; 

            try
            {
                if (m_LocalView.m_App.ActiveDocument.FullName.IndexOf(".doc") == -1)
                {
                    newFile = true;

                }

                if ((Word.WdSaveFormat)m_LocalView.m_App.ActiveDocument.SaveFormat != Word.WdSaveFormat.wdFormatDocument97)
                {
                    object filename = (newFile?
                                        m_LocalView.m_App.ActiveDocument.FullName + ".doc":
                                        m_LocalView.m_App.ActiveDocument.FullName.Replace("docx", "doc"));
                    object missing = System.Reflection.Missing.Value;  
                    object fileformat = Word.WdSaveFormat.wdFormatDocument97;

                    
                    m_LocalView.m_App.ActiveDocument.SaveAs(
                                                    ref filename,
                                                    ref fileformat,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing,
                                                    ref missing);
                                                    
            }

                DocumentInfo info = new DocumentInfo(m_LocalView.m_App.ActiveDocument.FullName, m_LocalView.m_App.ActiveDocument.Name);

                m_LocalView.DoLookupRemoteCopy(info);
                if (info.m_DocEntry == null)
                    m_LocalView.DoSaveDocumentInCloud();
                else
                    m_LocalView.m_DocInfo = info;

                this.ShareDocument();

                //in other case the getAclList returns wrong values instead of list shared users
                System.Threading.Thread.Sleep(2000);
                ShareInfoCollection infoShare = new ShareInfoCollection(m_LocalView.m_DocInfo.m_DocEntry);
                m_LocalView.DoGetDocumentAcl(infoShare);

                if (infoShare.m_Feed.Entries.Count() != 0 && checkBoxSharedNotification.Checked)
                    this.SendNotification(infoShare.m_Feed,
                                          this.ShareSubject.Text,
                                          this.ShareMsg.Text,
                                          this.m_LocalView.GetInviteUri(),
                                          m_LocalView.m_DocInfo.m_Name,
                                          MailNotificationTypes.Share);

                m_Tree.InitTree();
                FeedWrapper<Google.Documents.Document> feed = new FeedWrapper<Google.Documents.Document>();
                m_LocalView.DoGetDocuments(feed);

                foreach (Google.Documents.Document entry in feed.m_Feed.Entries) m_Tree.AddDocumentToCollection(entry);

                m_Tree.ShowTree();
            }
            catch (GDataRequestException ex)
            {
                m_TS_UI.SetForeColor(StatusMsgShare, Color.Red);
                m_TS_UI.SetText(StatusMsgShare, Properties.Resources.ErrorPrefix + ex.Message);
                m_TS_UI.SetVisible(StatusMsgShare, true);
                MessageBox.Show("Google Docs has encountered an API issue \n. In order to continue sharing operation \n please reopen the new uploaded Google.Documents.Document from Cloud.", "API Error");
            }
            catch (Exception ex)
            {
                m_TS_UI.SetForeColor(StatusMsgShare, Color.Red);
                m_TS_UI.SetText(StatusMsgShare, Properties.Resources.ErrorPrefix + ex.Message);
                m_TS_UI.SetVisible(StatusMsgShare, true);
                //Console.WriteLine(ex.Message);
            }
            finally
            {
                m_TS_UI.SetEnabled(ShareButton, true);
                m_TS_UI.SetEnabled(UpdateBtn, true);
            }
        }

        private void tabPage1_Enter(object sender, EventArgs e)
        {
            this.documentsView.Height = this.MyGDocsTabControl.Height - 60;
            this.documentsView.Width = this.MyGDocsTabControl.Width - 30;
        }

        private bool processNewDocument(Google.Documents.Document d, Document.DownloadType type, string fileName)
        {
            this.exportDialog.Filter = "Word|*.doc|Word 2007|*.docx";//|Comma seperated|*.csv";
            this.exportDialog.FileName = fileName;

            if (this.exportDialog.ShowDialog() == DialogResult.OK)
            {
                switch (d.Type)
                {
                    case Google.Documents.Document.DocumentType.Document:
                        type = Google.Documents.Document.DownloadType.doc; break;
                        //switch (this.exportDialog.FilterIndex)
                        //{
                        //    case 1:
                        //        type = Document.DownloadType.xls;
                        //        break;
                        //    case 2:
                        //        type = Document.DownloadType.csv;
                        //        break;
                        //}
                        //break;
                }

                DownloadInfo info = new DownloadInfo(d, type);
                m_LocalView.DoDownloadDocument(info);

                if (info.m_Stream != null)
                {
                    try
                    {
                        m_LocalView.DoSaveDocumentContent(this.exportDialog.OpenFile(), info.m_Stream);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show(ex.Message);
                        return false;
                    }

                    DocumentInfo chk_info = new DocumentInfo(null, null);
                    chk_info.m_DocEntry = d.DocumentEntry;
                    chk_info.m_FullName = this.exportDialog.FileName;
                    m_LocalView.DoRegisterLocalCopy(chk_info);
                }

                return true;
            }

            return false;
        }

        private bool processExistedDocument(Google.Documents.Document d, Document.DownloadType type, string fileName)
        {
            this.exportDialog.FileName = fileName;

            Collision m_CollisionDialog = new Collision();
            DialogResult m_Result = m_CollisionDialog.ShowDialog();

            if (m_Result == DialogResult.OK && m_CollisionDialog.m_ServerToLocal.Checked)
            {
                DownloadInfo info = new DownloadInfo(d, type);
                m_LocalView.DoDownloadDocument(info);

                if (info.m_Stream != null)
                {
                    try
                    {
                        foreach ( Word.Document wb in m_LocalView.m_App.Documents)
                        {
                            object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
                            object originalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;
                            object routeDocument = true;
                            
                            if (wb.Name == d.Title)
                                wb.Close(ref saveChanges, ref originalFormat, ref routeDocument);

                        }
                        //m_LocalView.m_App.ActiveWorkbook.Close(false, null, false);
                        m_LocalView.DoSaveDocumentContent(this.exportDialog.OpenFile(), info.m_Stream);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show(ex.Message);
                        return false;
                    }
                }

                return true;
            }

            return false; 
        }

        private void documentsView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            Google.Documents.Document d = e.Node.Tag as Document;
            // fill the filter based on the Google.Documents.Document type
            if ((d == null) || (d.Type != Document.DocumentType.Document)) 
                return;

            DocumentInfo chk_info = new DocumentInfo(null, null);
            chk_info.m_DocEntry = d.DocumentEntry;
            m_LocalView.DoLookupLocalCopy(chk_info);

            Document.DownloadType type = Document.DownloadType.doc;
            bool processResult = false;

            if (chk_info.m_FullName == null)
                processResult = processNewDocument(d, type, d.Title.Replace(".docx", ".doc"));
            else
                processResult = processExistedDocument(d, type, chk_info.m_FullName.Replace(".docx", ".doc"));

            //m_LocalView.DoOpenLocalCopy(this.exportDialog.FileName);

            if (processResult)
            {
                m_LocalView.DoOpenLocalCopyShared(this.exportDialog.FileName);
                m_LocalView.UpdateDocumentInfo();
                }
            else
                m_LocalView.DoOpenLocalCopyNotShared(this.exportDialog.FileName);

            UpdateBtn.Enabled = true;
            
        }

        private void Explorer_Resize(object sender, EventArgs e)
        {
            documentsView.Width = Explorer.Width - 30;
            documentsView.Height = Explorer.Height - 30;
        }

        private void documentsView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (documentsView.SelectedNode == null) return;
                Google.Documents.Document d = e.Node.Tag as Google.Documents.Document;
                if (d == null) return;
                if (d.Type == Google.Documents.Document.DocumentType.Folder) return;

                ContextMenu treeContextMenu = new ContextMenu();
                treeContextMenu.MenuItems.Add("Open in Cloud", OnOpenInCloud);
                System.Drawing.Point pt = new System.Drawing.Point(documentsView.SelectedNode.Bounds.Left,
                                     documentsView.SelectedNode.Bounds.Bottom);
                try
                {
                    treeContextMenu.Show(documentsView, pt);
                }
                catch (Exception ex)
                { }
            }
        }

        private void OnOpenInCloud(Object sender, EventArgs e)
        {
            if (documentsView.SelectedNode == null) return;
            Google.Documents.Document d = documentsView.SelectedNode.Tag as Google.Documents.Document;
            if (d == null) return;
            DocumentInfo info = new DocumentInfo(null, null);
            info.m_DocEntry = d.DocumentEntry;

            m_LocalView.DoOpenDocumentInCloud(info);
        }

        private void documentsView_MouseDown(object sender, MouseEventArgs e)
        {
            SetSelectedNodeByPosition(documentsView, e.X, e.Y);

            if (documentsView.SelectedNode == null) { return; }

            if (e.Button == MouseButtons.Right) { return; }

        }

        private static void SetSelectedNodeByPosition(TreeView tv, int mouseX, int mouseY)
        {
            TreeNode node = null;

            try
            {

                System.Drawing.Point pt = new System.Drawing.Point(mouseX, mouseY);

                tv.PointToClient(pt);

                node = tv.GetNodeAt(pt);

                tv.SelectedNode = node;

                if (node == null) return;

                if (!node.Bounds.Contains(pt)) { return; }

            }
            catch { }
            return;
        }

        public long LookAtContactsCount()
        {
            long l = ContactListBox.Items.Count;
            return l;
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            m_TS_UI.SetVisible(StatusMsgExplorer, false);
            
            try
            {
                BuildDocuments(); 
            }
            catch (Exception ex)
            {
                m_TS_UI.SetForeColor(StatusMsgExplorer, Color.Red);
                m_TS_UI.SetText(StatusMsgExplorer, Properties.Resources.ErrorPrefix + ex.Message);
                m_TS_UI.SetVisible(StatusMsgExplorer, true);
            }
        }

        private void RegistrationLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Registration regForm = new Registration(m_LocalView.m_db);
            if (regForm.ShowDialog() == DialogResult.OK)
            {
                UserName.Enabled = true;
                Password.Enabled = true;
                checkRemember.Enabled = true;
                LoginButton.Enabled = true;
                RegistrationLink.Visible = false;
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                Process.Start(Properties.Resources.AppUrl);
            }
            catch (Win32Exception)
            {
                //nothing is registered to handle URLs, so let's use IE!
                Process.Start("IExplore.exe", Properties.Resources.AppUrl);
            } 
 
        }

        private void UpdateBtn_Click(object sender, EventArgs e)
        {
            m_TS_UI.SetEnabled(UpdateBtn, false);
            m_TS_UI.SetVisible(StatusMsgUpdate, false);

            try{
                DocumentInfo info = new DocumentInfo(m_LocalView.m_App.ActiveDocument.FullName,
                                                     m_LocalView.m_App.ActiveDocument.Name);
                m_LocalView.DoLookupRemoteCopy(info); 
                if (info.m_DocEntry != null)
                {
               
                    m_LocalView.DoUpdateDocument();

                    ShareInfoCollection infoShare = new ShareInfoCollection(m_LocalView.m_DocInfo.m_DocEntry);
                    m_LocalView.DoGetDocumentAcl(infoShare);

                    if (infoShare.m_Feed.Entries.Count() != 0 && checkBoxUpdateNotification.Checked)
                        this.SendNotification(infoShare.m_Feed,
                                              this.UpdSubject.Text,
                                              this.UpdMsg.Text,
                                              this.m_LocalView.GetInviteUri(),
                                              m_LocalView.m_DocInfo.m_Name,
                                              MailNotificationTypes.Update);
                }
            }
            catch (GDataRequestException ex)
            {
                m_TS_UI.SetForeColor(StatusMsgUpdate, Color.Red);
                m_TS_UI.SetText(StatusMsgUpdate, Properties.Resources.ErrorPrefix + ex.Message);
                m_TS_UI.SetVisible(StatusMsgUpdate, true);
            }
            catch (Exception ex)
            {
                m_TS_UI.SetForeColor(StatusMsgUpdate, Color.Red);
                m_TS_UI.SetText(StatusMsgUpdate, Properties.Resources.ErrorPrefix + ex.Message);
                m_TS_UI.SetVisible(StatusMsgUpdate, true);

                //Console.WriteLine(ex.Message);
            }
            finally
            {
                m_TS_UI.SetEnabled(UpdateBtn, true);
            }
        }

        private void MyGDocsTabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //reset all errors messages
            m_TS_UI.SetVisible(StatusMessage, false);
            m_TS_UI.SetVisible(StatusMsgShare, false);
            m_TS_UI.SetVisible(StatusMsgUpdate, false);
            m_TS_UI.SetVisible(StatusMsgExplorer, false);
        }

        private void SignIn_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            ///int it = 100;
        }

        private void LoginButton_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                e.Handled = true;
                this.button1_Click(sender, null); 
            }

        }

        private void MyGDocsTabControl_Enter(object sender, EventArgs e)
        {
            //int i = 100;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            //Send query by post
            System.Net.WebClient wc = new System.Net.WebClient();
            System.Collections.Specialized.NameValueCollection nvc =
                new System.Collections.Specialized.NameValueCollection();
            nvc.Add("appid", Properties.Settings.Default.AppId);
            nvc.Add("context",
                Globals.ThisAddIn.Application.ActiveDocument.Content.Text);
            XDocument xdoc = XDocument.Parse(Encoding.UTF8.GetString(
                wc.UploadValues("http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction",
                "POST", nvc)));
            //Iterate through keywords
            VSTO.SmartTag tag = new OCISmartTag(
                "http://www.upriseapps.com/#officeincloud", 
                "Office In Cloud");
            VSTO.Action myAction;
         

            myAction =
                new VSTO.Action("Open in Web");
            tag.Actions =
              new VSTO.Action[] { myAction };

            myAction.Click += new Microsoft.Office.Tools.Word.ActionClickEventHandler(myAction_Click); 

            StringBuilder keywords = new StringBuilder();
            foreach (var xresult in xdoc.Elements().First().Elements())
            {
                keywords.AppendLine(xresult.Value);
                tag.Terms.Add(xresult.Value); 
                tag.Expressions.Add(new System.Text.RegularExpressions.Regex("[ ]" + xresult.Value + "[ |.]"));

                
                string str = xresult.Value;
                string[] strs = str.Split(new char[] { ' ' });

                foreach (string s in strs)
                {
                    foreach (Word.Range word in Globals.ThisAddIn.Application.ActiveDocument.Words)
                    {
                        //If we trim, we need to highlight less than the size of the word otherwise the space after
                        //the word is highlighted as well.
                        if (string.Compare(word.Text.Trim(), s, true, CultureInfo.InvariantCulture) == 0)
                        {
                            word.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdYellow;
                        }
                    }
                }
                 

            }



            tag.Terms.Add("Microsoft");
            tag.Terms.Add("Office");
            tag.Expressions.Add(new System.Text.RegularExpressions.Regex("[A|a]ndriy\\s[K|k]andzyuba"));
            //Show a message box!
            //System.Windows.Forms.MessageBox.Show(
            //    keywords.ToString(), "Keywords");
            
            
            KeywordsBox.Text = keywords.ToString();
            //Globals.ThisAddIn.Application.ActiveDocument.
            Globals.ThisAddIn.Application.ActiveDocument.GetVstoObject().VstoSmartTags.Add(tag);
            Globals.ThisAddIn.Application.ActiveDocument.RecheckSmartTags();
            


            //Globals.ThisAddIn.Application.ActiveDocument.GetVstoObject().SmartTags.ReloadRecognizers();
            


        }

        

        void myAction_Click(object sender, VSTO.ActionEventArgs e)
        {
            e.Range.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdYellow;
            MessageBox.Show(String.Format(
              "Open in LinkedIn",
              e.Range));
        }
    }

}
